package com.lagou.demo.service.impl;

import com.lagou.demo.model.Article;
import com.lagou.demo.repository.ArticleRepository;
import com.lagou.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Description 类功能描述
 * @Author 郭汝诚
 * @Date 2020/6/21 18:04
 * @Version 1.0
 **/
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public Article findArticleById(Integer id) {
        Optional<Article> byId = articleRepository.findById(id);
        if (byId.isPresent()){
            Article article = byId.get();
            return article;
        }
        return null;
    }

    /**
     * 分页查询article
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Article> queryArticlePage(Integer page, Integer size) {
        //避免前端没有传分页数据，造成查询出错
        if (page == null || page <= 0){ //传入错误页码时，进行页码修正
            page = 0;
        }
        if (size == null || size <= 0){ //传入错误页大小时，进行页大小修正
            size = 3;
        }
        //构建分页条件
        Pageable pageable = PageRequest.of(page,size,Sort.by("id"));
        //返回分页查询结果
        return articleRepository.findAll(pageable);
    }
}
